/*
 * Copyright 2011-2012 OpenAjax Alliance
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/**
 * @file sidebar.js
 *
 * @desc Utilities to support the selection and viewing of sidebar information
 */

Components.utils.import("resource://oaa-cache-inspector/cache-inspector-common.js");

/* ---------------------------------------------------------------- */
/*                          OAA_CI Object                           */ 
/* ---------------------------------------------------------------- */

if (typeof OAA_CI === "undefined") {
  var OAA_CI = {};
}

/**
 * @function OAA_CI.updateProgress
 *
 * @desc updated progress information on evaluating a document
 */

OAA_CI.updateProgress = function (message, percent) {

  if (OAA_CI.prog_meter) {
    OAA_CI.prog_meter.value = percent;
  }

  if (OAA_CI.prog_message) {
    OAA_CI.prog_message.value = message;
  }

};

/**
 * @function OAA_CI.hideMeter
 *
 * @desc Hides progress bar used to provide information on evaluating a document
 */

OAA_CI.hideMeter = function () { 
  OAA_CI.meter.hidden = true; 
  OAA_CI.evaluate_button.disabled = false; 
};

/**
 * @function OAA_CI.showMeter
 *
 * @desc Shows progress bar used to provide information on evaluating a document
 */

OAA_CI.showMeter = function () { 
  OAA_CI.meter.hidden = false; 
  OAA_CI.evaluate_button.disabled = true; 
};

/**
 * @function OAA_CI.turnOffHighlighting
 *
 * @desc turn off highlighting for the last cache item that was
 *       highlighted (see highlightCacheItem)
 */

OAA_CI.turnOffHighlighting = function () {

  OAA_WEB_ACCESSIBILITY.util.highlightModule.removeHighlight();

};

/**
 * highlightCacheItem
 *
 * @desc cache_item Object OAA Cache item
 *
 * @param  {Object}  doc          -  DOM that contains the cache items
 * @param  {Object}  cache_items  -  cache item object or list of cache item objects
 *
 * @return nothing
 */

OAA_CI.highlightCacheItems = function(doc, cache_items) {

  OAA_WEB_ACCESSIBILITY.util.highlightModule.highlightCacheItems(cache_items);

};

/**
 * highlightNodeResults
 *
 * @desc cache_item Object OAA Cache item
 *
 * @param {Object}          doc          - DOM that contains the cache items
 * @param {Object or Array} node_results - node result object or an array of node result objects
 *
 * @return nothing
 */

OAA_CI.highlightNodeResults = function(doc, node_results) {

  OAA_WEB_ACCESSIBILITY.util.highlightModule.highlightNodeResults(node_results);

};

/**
 * @function getCacheIdFromTree
 *
 * @memberOf OAA_CI
 *
 * @desc Return the cache ID of a tree element specified by a selection index.
 *
 * @param {XUL tree} tree - XUL tree with selected cache element.
 * @param {int} index - Tree row index of selected cache element.
 */

OAA_CI.getCacheIdFromTree = function (tree, index) {

  

  var col_id = tree.columns.getFirstColumn();
  
  if (col_id) {
    try {
      return tree.view.getCellValue(index, col_id);
    }
    catch (err) {
      return null;
    }
  }
  else {
    return null;
  }

};

/**
 * evaluateDocument
 *
 * @desc opens the log information window
 *
 * @param window Object window object of document to be analyzed
 *
 * @return nothing
 */

OAA_CI.evaluateDocument = function () {

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Evaluating Document");

  var doc;
  var title;
  var url;

  try {
    doc = window.content.document;
    title = doc.title;
    url = window.content.location.href;
  } catch(e) {
    doc  = window.opener.parent.content.document;
    title = doc.title;
    url = window.opener.parent.location.href;
  } // end try
  
  OAA_CI.document = doc;
  
  var prefs = OAA_WEB_ACCESSIBILITY_PREF.util.getPreferences();
  
  var emc = prefs.show_results_element_manual_checks;
  var pmc = prefs.show_results_page_manual_checks;
  var sp  = prefs.show_results_pass;
  var sh  = prefs.show_results_hidden;

  OAA_WEB_ACCESSIBILITY.util.highlightModule.initHighlight(doc, emc, pmc, sp, sh);

  OAA_CI.updateProgress("", 0);

  OpenAjax.a11y.CONSOLE_MESSAGES = true;
  OpenAjax.a11y.SUPPORTS_EVENT_ANALYSIS = true;  // enable collecting information about events

  OAA_CI.ruleset = OpenAjax.a11y.all_rulesets.getRuleset(prefs.ruleset_id); 

  if (OAA_CI.ruleset) {

    OAA_CI.ruleset.setEvaluationLevel(prefs.wcag20_level);
    OAA_CI.ruleset.setRecommendedRulesEnabled(prefs.wcag20_recommended_rules_enabled);
    OAA_CI.ruleset.setBrokenLinkTesting(prefs.broken_links);
    OAA_CI.ruleset.setDataTableAssumption(!prefs.layout_tables);
  
    OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Preforming Evaluation: " + title + " " + url);
    OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("    Ruleset ID: " + OAA_CI.ruleset.ruleset_id);
    OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("    WCAG Level: " + OAA_CI.ruleset.wcag20_level);
    OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("  Broken Links: " + OpenAjax.a11y.URL_TESTING_ENABLED);

    OAA_CI.ruleset.evaluate(url, title, doc, OAA_CI.updateProgress, true);
  }
  else {
    OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("  ** Ruleset with the id '" + preferences.ruleset_id + "' not found!!");
  }

  OAA_CI_UTILS.result  = null;
  OAA_CI_UTILS.log     = null;

  if (OAA_CI_UTILS && OAA_CI.ruleset && OAA_CI.ruleset.result) {
    OAA_CI_UTILS.result  = OAA_CI.ruleset.result;
    OAA_CI_UTILS.log     = OAA_CI.ruleset.log;
  }

};

/**
 * @function setTextNode
 *
 * @memberOf OAA_CI
 *
 * @desc Creates a DOM Text Node and appends it to the element node
 *
 * @param {DOM node}  node  - DOM Element node    
 * @param {String}  text  - Text content to add to a DOM element node     
 */

OAA_CI.setTextNode = function (node, text) {

  var text_node = document.createTextNode(text);

  OAA_CI.removeChildNodes(node);
  node.appendChild(text_node);

};

/**
 * @function addTreeItemMessage
 *
 * @memberOf OAA_CI
 *
 * @desc Sets a message 
 *
 * @param {XULTreechildren}  node  - XUL treechildren element node    
 *
 * @param {String}  message  - Message text     
 * @param {String}  style    - Style class for styling the cell     
 */

OAA_CI.addTreeItemMessage = function (treechildren, message, style, column) {

  if (typeof column === 'undefined') column = 2;

  var treeitem = document.createElement('treeitem');
  var treerow  = document.createElement('treerow');

  for (var i = 1; i < column; i++) {
    var treecell = document.createElement('treecell');
    treecell.setAttribute('label', "");
    treecell.setAttribute('value', style);
    treerow.appendChild(treecell);
  }  

  treecell = document.createElement('treecell');
  treecell.setAttribute('label', message);
  treecell.setAttribute('value', style);
  if (style) treecell.setAttribute('properties', style);
  treerow.appendChild(treecell);

  treeitem.appendChild(treerow);
  treechildren.appendChild(treeitem);  

};

/* ---------------------------------------------------------------- */
/*      Item Properties and Rule Information Dialog Boxes           */ 
/* ---------------------------------------------------------------- */


/**
 * @function OAA_CI.showRulePropertiesDialog
 *
 * @desc Show and update information about a rule result for a cache item
 *
 * @param {RuleResult | NodeResult} result_object  -  Rule result or node result object 
 */
 
OAA_CI.showRulePropertiesDialog = function (result_object) { 

  if (!OAA_CI.rule_properties_dialog || !OAA_CI.rule_properties_dialog.rule_properties) {
    if (result_object) OAA_CI.rule_properties_dialog = window.openDialog("chrome://oaa-cache-inspector/content/rule_properties/rule-properties.xul", "_rule_properties_dialog", "", result_object);     
  } else {
    if (result_object && result_object.getRuleSummary) {
      OAA_CI.rule_properties_dialog.rule_properties.update(result_object);
      OAA_CI.rule_properties_dialog.focus();
    }
    else {
      OAA_CI.rule_properties_dialog.rule_properties.clear();    
      OAA_CI.rule_properties_dialog.focus();
    }
  }
    
};

/**
 * @function OAA_CI.showCacheItemPropertiesDialog
 *
 * @desc Builds a button to show and update the node results of a cache item
 *
 * @param {CacheItem} cache_item  -  cache item object
 */
 
OAA_CI.showCacheItemPropertiesDialog = function (cache_item) { 

  if (!OAA_CI.cache_item_properties_dialog || !OAA_CI.cache_item_properties_dialog.cache_item_properties) {
    if (cache_item) OAA_CI.cache_item_properties_dialog = window.openDialog("chrome://oaa-cache-inspector/content/item_properties/cache-item-properties.xul", "_cache_item_properties_dialog", "", cache_item);     
  } else {
    if (cache_item && typeof cache_item.tag_name !== 'undefined') {
      OAA_CI.cache_item_properties_dialog.cache_item_properties.update(cache_item);
      OAA_CI.cache_item_properties_dialog.focus();
    }
    else {
      OAA_CI.cache_item_properties_dialog.cache_item_properties.clear();
    }
  }
  
};


/**
 * @function OAA_CI.initSidebar
 *
 * @desc Initialize sidebar bar information 
 */

OAA_CI.initSidebar = function (type) {

  OAA_CI.updateRulesetInformation();
  
// Initializes variables with references to XUL controls in the view  

  OAA_CI.ElementResultView.init();
  OAA_CI.ElementView.init();
  OAA_CI.RuleCategoryView.init();
  OAA_CI.RuleResultView.init();
//  OAA_CI.RuleSummaryView.init();

  switch (type) {

  case 'element':
    OAA_CI.ElementView.show();
    OAA_CI.ElementResultView.show();
    
    OAA_CI.RuleCategoryView.hide();
//    OAA_CI.RuleSummaryView.hide();
    OAA_CI.RuleResultView.hide();
    
    OAA_CI.update = OAA_CI.ElementView.update;
    OAA_CI.clear  = OAA_CI.ElementView.clear;
    break;

  case 'summary':
    OAA_CI.RuleCategoryView.show(true);
    OAA_CI.RuleResultView.show();
    
    OAA_CI.ElementView.hide();
    OAA_CI.ElementResultView.hide();
//    OAA_CI.RuleSummaryView.hide();
    
    OAA_CI.update = OAA_CI.RuleCategoryView.update;
    OAA_CI.clear  = OAA_CI.RuleCategoryView.clear;
    break;

  case 'category':
  default:
    OAA_CI.RuleCategoryView.show(false);
    OAA_CI.RuleResultView.show();
    
    OAA_CI.ElementView.hide();
    OAA_CI.ElementResultView.hide();
//    OAA_CI.RuleSummaryView.hide();
    
    OAA_CI.update = OAA_CI.RuleCategoryView.update;
    OAA_CI.clear  = OAA_CI.RuleCategoryView.clear;
    break;
    
  }

  OAA_CI_UTILS.setFocusSummary();

};

/**
 * @function OAA_CI.clearSidebar
 *
 * @desc Clear sidebar bar information 
 */

OAA_CI.clearSidebar = function () {

  
  var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIWebNavigation)
  .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
  .rootTreeItem
  .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIDOMWindow);

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Clearing Sidebar: " + mainWindow.oaa_sidebar_name);

  switch (mainWindow.oaa_sidebar_type) {

  case 'element':
    OAA_CI.ElementView.clear();
    break;

  case 'summary':
    OAA_CI.RuleCategoryView.clear();
    break;

  case 'category':
    OAA_CI.RuleCategoryView.clear();
    break;

  default:
    break;

  }

};

/**
 * @function OAA_CI.updateRulesetInformation
 *
 * @desc Update the sidebar content
 */

OAA_CI.updateRulesetInformation = function () {

  var wcag20_nls = OpenAjax.a11y.all_wcag20_nls.getNLS();

  var prefs = OAA_WEB_ACCESSIBILITY_PREF.util.getPreferences();
  
  var ruleset = OpenAjax.a11y.all_rulesets.getRuleset(prefs.ruleset_id);

  var label_ruleset = document.getElementById('ID_LABEL_RULESET');  
  label_ruleset.value = ruleset.ruleset_title;
  
  var label_level   = document.getElementById('ID_LABEL_LEVEL');  
  label_level.value   = wcag20_nls.getNLSWCAG20Level(prefs.wcag20_level);

};

/**
 * @function OAA_CI.updateSidebar
 *
 * @desc Update the sidebar content
 */

OAA_CI.updateSidebar = function () {

  var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIWebNavigation)
  .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
  .rootTreeItem
  .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIDOMWindow);
  
  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Updating Sidebar: " + mainWindow.oaa_sidebar_name);

//  if (typeof OAA_CI.update == 'function')  OAA_CI.update();

  OAA_CI.updateRulesetInformation();

  switch (mainWindow.oaa_sidebar_type) {

  case 'element':
    OAA_CI.ElementView.update(mainWindow.oaa_sidebar_name);
    break;

  case 'summary':
    OAA_CI.RuleCategoryView.update();
    break;

  case 'category':
  default:
    OAA_CI.RuleCategoryView.update();
    break;
    
  }
};

/**
 * @function OAA_CI.updateEvaluation

 *
 * @desc Update the sidebar 
 */

OAA_CI.updateEvaluation = function () {

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Updating Evaluation: Start");

  OAA_CI.clearSidebar();
  OAA_CI.evaluateDocument();    
  OAA_CI.updateSidebar();

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Updating Evaluation: End");

};


/**
 * @function OAA_CI.onTabSelect
 *
 * @desc Respond to a locationChange event by calling the showTransition
 *       function for the current sidebar.
 */

OAA_CI.onTabSelect = function (event) {

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Tab Select: Start");

  OAA_CI.updateView();

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Tab Select: End");

};

/**
 * @function OAA_CI.showTransition
 *
 * @desc Respond to a locationChange event: While new page is loading,
 *       show the progress meter, remove stale data and show message.
 */

OAA_CI.showTransition = function () {

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Show Transition: Start");

  OAA_CI.turnOffHighlighting();
  OAA_CI.showMeter();
  OAA_CI.clearSidebar();

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Show Transition: End");

};

/**
 * @function OAA_CI.updateView
 *
 * @desc Evaluate the new document; hide the progress meter to indicate
 *       loading of the new page has completed; reset isInitialized
 *       variables for all tab panel views so that subsequent calls to
 *       showCacheItems functions result in repopulation with fresh data.
 *       Call showCacheItems for the currently selected tab panel view.
 */

OAA_CI.updateView = function () {

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Update View: Start");

  var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIWebNavigation)
  .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
  .rootTreeItem
  .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIDOMWindow);

//  OAA_CI.turnOffHighlighting();
  OAA_CI.initSidebar(mainWindow.oaa_sidebar_type);
  OAA_CI.evaluateDocument();
  OAA_CI.hideMeter();
  OAA_CI.updateSidebar();

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Update View: End");

};

OAA_CI.progressListener = OAA_WEB_ACCESSIBILITY_UTILS.getProgressListener(
  OAA_CI.showTransition, OAA_CI.updateView);
  

/**
 * @function OAA_CI.onLoad
 *
 * @desc Initialize sidebar and populate its default tabpanel.
 */

OAA_CI.onLoad = function () {

  var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIWebNavigation)
  .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
  .rootTreeItem
  .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIDOMWindow);

  mainWindow.gBrowser.addProgressListener(OAA_CI.progressListener);
  mainWindow.gBrowser.tabContainer.addEventListener("TabSelect", OAA_CI.onTabSelect, false);

  OAA_CI.oaa_log_window = null;
  OAA_CI.oaa_results_window = null;

//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Evaluation Complete");

//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Setting Toolbar and Menus Complete");

  OAA_CI.meter           = document.getElementById('ID_PROGRESS_METER');
  OAA_CI.evaluate_button = document.getElementById('ID_BUTTON_EVALUATE');
  
//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Progress meter:  " + OAA_CI.meter);  
//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Evaluate Button: " + OAA_CI.evaluate_button);  
  
  // This needs to be a global variable in the window
  OAA_WEB_ACCESSIBILITY_PREF_CALLBACK = function () {
      OAA_CI.updateEvaluation();  
  };
  
  if (typeof mainWindow.oaa_sidebar_type != 'string') OAA_CI_UTILS.showRuleSummary('WCAG20');
  else OAA_CI.updateView();

};

/**
 * @function OAA_CI.onUnload
 *
 * @desc onunLoad event handler that resets object properties
 *
 * @return nothing
 */

OAA_CI.onUnload = function(cache) {

  OAA_WEB_ACCESSIBILITY_PREF_CALL_BACK = null;
  
  var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIWebNavigation)
  .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
  .rootTreeItem
  .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIDOMWindow);


  mainWindow.gBrowser.removeProgressListener(OAA_CI.progressListener);
  mainWindow.gBrowser.tabContainer.removeEventListener("TabSelect", ainspectorSidebar.onTabSelect, false);  

  OAA_CI_UTILS.setStateToolbarAndMenus(mainWindow, "","");

  OAA_CI.turnOffHighlighting();
  
  if (OAA_CI.cache_item_properties_dialog && OAA_CI.cache_item_properties_dialog.cache_item_properties) {
    OAA_CI.cache_item_properties_dialog.close();
  }

  if (OAA_CI.rule_properties_dialog && OAA_CI.rule_properties_dialog.rule_properties) {
    OAA_CI.rule_properties_dialog.close();
  }  


};

window.addEventListener("load",   function () { OAA_CI.onLoad();   }, false);
window.addEventListener("unload", function () { OAA_CI.onUnload(); }, false);
